<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>购物车示例</title>
</head>
<body>
  <div id="app">
    <h3>购物车</h3>
    <div v-for="goods in cart">
      编号:{{ goods.id }},标题: {{ goods.title }},价格: {{ goods.price }},
      <button v-on:click="handleRemove(goods.id)">删除</button>
    </div>
    <div>合计: {{ total }}</div>

    <hr>
    <h3>推荐商品</h3>
    <div v-for="goods in recommend">
      编号:{{ goods.id }},标题: {{ goods.title }},价格: {{ goods.price }},
      <button v-on:click="handleAdd(goods)">加入购物车</button>
    </div>
  </div>

  <script src="./lib/vue.global.js"></script>
  <script>
    // 推荐商品数据
    const recommend = Array(6).fill(null).map((item, index) => ({
      id: index + 1,
      title: '商品标题' + (index + 1),
      price: Math.floor(Math.random() * 99) + 9.9,
    }))
  </script>
  <script>
    // 在全局有 Vue 对象可直接调用

    // 创建应用实例
    const app = Vue.createApp({
      data() { // Model
        return {
          recommend, // 推荐商品
          cart: [], // 购物车数组
        }
      },
      computed: {
        total() {
          return this.cart.reduce((sum, item) => sum + item.price, 0)
        }
      },
      methods: { // 方法
        handleAdd(goods) { // 实现加入购物车的逻辑
          console.log('加入购物车:', goods)
          this.cart.push({...goods})
        },
        handleRemove(id) { // 删除购物车商品
          this.cart = this.cart.filter(item => item.id !== id)
        }
      },
    })
    // 挂载
    app.mount('#app')
  </script>
</body>
</html>